package com.hhkj.admin.bank.common.mybatis.handler;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.util.HashMap;
import java.util.Map;

/**
 * StrStrMapHandler
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/5/12 10:37
 */
@Slf4j
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StrStrMapHandler extends AbstractJsonTypeHandler<Map<String, String>>
{
    @Override
    protected Map<String, String> parse(String json)
    {
        Map<String, String> value = new HashMap<>();
        JSONObject jsonObject = JSONObject.parse(json);
        for (Map.Entry<String, Object> stringObjectEntry : jsonObject.entrySet()) {
            value.put(stringObjectEntry.getKey(), (String) stringObjectEntry.getValue());
        }
        return value;
    }

    @Override
    protected String toJson(Map<String, String> obj)
    {
        return new JSONObject(obj).toJSONString(
                JSONWriter.Feature.WriteNullListAsEmpty,
                JSONWriter.Feature.WriteMapNullValue,
                JSONWriter.Feature.WriteNullStringAsEmpty
        );
    }
}
